//
//  NetworkStateMonitoring.m
//  NetworkDemo
//
//  Created by 万孟超 on 2021/9/9.
//

#import "NetworkStateMonitoring.h"
#import "RealReachability.h"

@implementation NetworkStateMonitoring

/**
 单例初始化方法
 */
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static id _sharedManager = nil;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[self alloc] init];
    });
    return _sharedManager;
}

/// 启动监测
- (void)startUp {
    GLobalRealReachability.hostForPing = @"www.baidu.com";
    [GLobalRealReachability startNotifier ];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkChanged:)
                                                 name:kRealReachabilityChangedNotification
                                               object:nil];
}

/// 网络状态监测回调
/// NetworkClient处理通知
/// @param notification 通知
- (void)networkChanged:(NSNotification *)notification {
    RealReachability *reachability = (RealReachability *)notification.object;
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    if (status == RealStatusUnknown) {
        NSLog(@"网络监测-未知");
    }else if (status == RealStatusNotReachable) {
        NSLog(@"网络监测-无网络");
    }else if (status == RealStatusViaWWAN) {
        NSLog(@"网络监测-窝蜂未知");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NETWORK_RETRY" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NETWORK_TIMEOUT_RETRY" object:nil];
    }else if (status == RealStatusViaWWAN2G) {
        NSLog(@"网络监测-窝蜂2G");
    }else if (status == RealStatusViaWWAN3G) {
        NSLog(@"网络监测-窝蜂3G");
    }else if (status == RealStatusViaWWAN4G) {
        NSLog(@"网络监测-窝蜂4G");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NETWORK_RETRY" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NETWORK_TIMEOUT_RETRY" object:nil];
    }else if (status == RealStatusViaWWAN5G) {
        NSLog(@"网络监测-窝蜂5G");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NETWORK_RETRY" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NETWORK_TIMEOUT_RETRY" object:nil];
    }else if (status == RealStatusViaWiFi) {
        NSLog(@"网络监测-WIFI");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NETWORK_RETRY" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NETWORK_TIMEOUT_RETRY" object:nil];
    }
}

@end
